<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS运动</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .wrapAll {
            padding: 10px;
        }

        .buttons button+button {
            margin-left: 10px;
        }

        .wrap {
            width: 1100px;
            height: 100px;
            border: 1px solid #333;
            margin-top: 10px;
            position: relative;
        }

        .sub {
            width: 100px;
            height: 100px;
            background-color: #6ff;
            position: absolute;
            /* left: 100px; */
        }
    </style>
</head>

<body>
    <div class="wrapAll">
        <div class="buttons">
            <button class="start">开始</button>
            <button class="pause">暂停</button>
            <button class="back">返回</button>
        </div>
        <div class="wrap">
            <div class="sub"></div>
        </div>
    </div>

</body>
<script>
    var start = document.getElementsByClassName("start")[0];
    var pause = document.getElementsByClassName("pause")[0];
    var back = document.getElementsByClassName("back")[0];
    var sub = document.getElementsByClassName("sub")[0];

    var timer = null;
    var cur = sub.offsetLeft;
    var speed = 2;
    // 正向运动
    start.onclick = function () {
        var end = 1000;
        clearInterval(timer);
        timer = setInterval(function () {
            cur += speed;
            sub.style.left = cur + "px";
            if (cur >= end) {
                clearInterval(timer);
                sub.style.left = end + "px";
            }
        }, 1);
    }

    // 暂停
    pause.onclick = function () {
        clearInterval(timer);
    }

    // 反向运动
    back.onclick = function () {
        var end = 0;
        clearInterval(timer);
        timer = setInterval(function () {
            cur -= speed;
            sub.style.left = cur + "px";
            if (cur <= 0) {
                clearInterval(timer);
                sub.style.left = end + "px";
            }
        }, 1);
    }

    
</script>

</html>